<template>
  <n-data-table
    :columns="columns"
    :data="data"
    :pagination="pagination"
    :bordered="false"
  />
  <n-modal
    v-model:show="showModal"
    class="custom-card"
    preset="card"
    title="是否删除"
    size="huge"
    :bordered="false"
    :style="bodyStyle"
  >
    确定删除该文章吗
    <template #footer>
      <div style="float: right;">
        <NButton type="tertiary" style="margin-right: 20px;" @click="showModal = false">取消</NButton>
        <NButton strong secondary type="success" @click="removeCartoon">确定</NButton>
      </div>
    </template>
  </n-modal>
</template>

<script setup lang='ts'>
import {GetAllEssay, DeleteEssay} from '../../api/api'
import { h, onMounted,ref,Ref } from 'vue'
import {NButton } from 'naive-ui'
import type { DataTableColumns } from 'naive-ui'
import { useRouter } from "vue-router";
const router = useRouter()

type Song = {
  essayAuthor: string
  essayTitle: string
  essayClicks: string
  essayTime: string
  essayId: number
}

onMounted(async () => {
  initCartoon()
})

const initCartoon = async () => {
  let essayData = await GetAllEssay()
  data.value = essayData.data
}

var data:Ref<Song[]> = ref([])
var showModal:Ref<boolean> = ref(false)
var rowCurrent = ref()

const createColumns = ({
  detail,
  remove
}: {
  detail: (row:Song) => void,
  remove: (row:Song) => void,
}): DataTableColumns<Song> => {
  return [
    {
      title: '标题',
      key: 'essayTitle',
      ellipsis: {
        tooltip: {
          contentStyle: {width:"700px"}
        }
      }
    },
    {
      title: '作者',
      key: 'essayAuthor',
    },
    {
      title: '点击量',
      key: 'essayClicks',
    },
    {
      title: '发布时间',
      key: 'essayTime',
    },
    {
      title: "",
      key: 'detail',
      render (row) {
        return h(
          NButton,
          {
            strong: true,
            tertiary: true,
            size: 'small',
            type: 'info',
            onClick: () => detail(row)
          },
          { default: () => '更多' }
        )
      }
    },
    {
      title: "",
      key: 'remove',
      render (row) {
        return h(
          NButton,
          {
            strong: true,
            tertiary: true,
            size: 'small',
            type: 'error',
            onClick: () => remove(row)
          },
          { default: () => '删除文章' }
        )
      }
    },
  ]
}

var columns = createColumns({
  detail(row:Song) {
    router.push({
      name: 'essayComment',
      params: {
        id: row.essayId
      }
    })
  },
  remove(row:Song) {
    showModal.value = true
    rowCurrent.value = row
  }
})

const removeCartoon = async () => {
  let res = await DeleteEssay({
    essayId: rowCurrent.value.essayId
  })
  if(res.state === "OK") {
    window.$message.success("删除成功!")
    initCartoon()
  }
}

const bodyStyle:object = {
  width: '400px',
}
  
const pagination:object = {pageSize:10}

</script>

<style lang='scss' scoped>
  
</style>